package com.terracloud.server.utils;

import com.terracloud.common.util.AsyncUtils;
import com.terracloud.server.common.data.page.PageData;
import org.springframework.data.domain.Page;

import java.util.concurrent.Callable;
import java.util.function.Function;

/**
 *
 * @author chenhainan
 * @since 2025/10/23
 */
public class PageDataUtils {

    public static <S, D> PageData<D> toPageData(Page<S> page, Function<S, D> mapper) {
        return new PageData<>(page.getContent().stream().map(mapper).toList(), page.getTotalPages(), page.getTotalElements(), page.hasNext());
    }

    public static <S, D> PageData<D> toPageDataAsync(Page<S> page, Function<S, D> mapper) throws Exception {
        final var callables = page.getContent().stream().map(s -> (Callable<D>) () -> mapper.apply(s)).toList();
        return new PageData<>(AsyncUtils.awaitAll(callables),
                page.getTotalPages(), page.getTotalElements(), page.hasNext());
    }

    public static <S,D> PageData<D> mapPageData(PageData<S> page, Function<S, D> mapper) {
        return new PageData<D>(page.getData().stream().map(mapper).toList(), page.getTotalPages(), page.getTotalElements(), page.hasNext());
    }

    public static <S,D> PageData<D> mapPageDataAsync(PageData<S> page, Function<S, D> mapper) throws Exception {
        final var callables = page.getData().stream().map(s -> (Callable<D>) () -> mapper.apply(s)).toList();
        return new PageData<>(AsyncUtils.awaitAll(callables),
                page.getTotalPages(), page.getTotalElements(), page.hasNext());
    }

}
